﻿using MathTutorPro.Data.Entities;
using MathTutorPro.Models.Requests;
using MathTutorPro.Models.Responses;
using MathTutorPro.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace MathTutorPro.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class GroupChatController : ControllerBase
    {
        private readonly IGroupChatService _groupChatService;
        private readonly ILogger<GroupChatController> _logger;

        public GroupChatController(
            IGroupChatService groupChatService,
            ILogger<GroupChatController> logger)
        {
            _groupChatService = groupChatService;
            _logger = logger;
        }

        /// <summary>
        /// 创建群组
        /// </summary>
        [HttpPost("groups")]
        public async Task<IActionResult> CreateGroup([FromBody] GroupCreateRequest request)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                var groupId = await _groupChatService.CreateGroupAsync(userId, request);
                return Ok(ApiResponse<int>.Success(groupId));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建群组失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 获取用户的群聊列表
        /// </summary>
        [HttpGet("groups")]
        public async Task<IActionResult> GetGroups()
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                var groups = await _groupChatService.GetUserGroupsAsync(userId);
                return Ok(ApiResponse<IEnumerable<GroupResponse>>.Success(groups));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取群组列表失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 获取群组消息
        /// </summary>
        [HttpGet("groups/{groupId}/messages")]
        public async Task<IActionResult> GetGroupMessages(
            int groupId,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                var messages = await _groupChatService.GetGroupMessagesAsync(userId, groupId, page, pageSize);
                return Ok(ApiResponse<IEnumerable<MessageResponse>>.Success(messages));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取群组消息失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 获取群组详情
        /// </summary>
        [HttpGet("groups/{groupId}")]
        public async Task<IActionResult> GetGroupDetail(int groupId)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                var group = await _groupChatService.GetGroupDetailAsync(userId, groupId);
                return Ok(ApiResponse<GroupDetailResponse>.Success(group));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取群组详情失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 加入群组
        /// </summary>
        [HttpPost("groups/{groupId}/join")]
        public async Task<IActionResult> JoinGroup(int groupId)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                await _groupChatService.JoinGroupAsync(userId, groupId);
                return Ok(ApiResponse.Success("加入群组成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加入群组失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 退出群组
        /// </summary>
        [HttpPost("groups/{groupId}/leave")]
        public async Task<IActionResult> LeaveGroup(int groupId)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                await _groupChatService.LeaveGroupAsync(userId, groupId);
                return Ok(ApiResponse.Success("退出群组成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "退出群组失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 获取群组成员
        /// </summary>
        [HttpGet("groups/{groupId}/members")]
        public async Task<IActionResult> GetGroupMembers(int groupId)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                var members = await _groupChatService.GetGroupMembersAsync(userId, groupId);
                return Ok(ApiResponse<IEnumerable<GroupMemberResponse>>.Success(members));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取群组成员失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 添加群组成员
        /// </summary>
        [HttpPost("groups/{groupId}/members")]
        public async Task<IActionResult> AddGroupMembers(
            int groupId,
            [FromBody] List<string> memberIds)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                await _groupChatService.AddGroupMembersAsync(userId, groupId, memberIds);
                return Ok(ApiResponse.Success("添加成员成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加群组成员失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 移除群组成员
        /// </summary>
        [HttpDelete("groups/{groupId}/members/{memberId}")]
        public async Task<IActionResult> RemoveGroupMember(int groupId, string memberId)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                await _groupChatService.RemoveGroupMemberAsync(userId, groupId, memberId);
                return Ok(ApiResponse.Success("移除成员成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "移除群组成员失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }

        /// <summary>
        /// 发送群组消息
        /// </summary>
        [HttpPost("groups/{groupId}/messages")]
        public async Task<IActionResult> SendMessage(
            int groupId,
            [FromBody] SendMessageRequest request)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                    return Unauthorized(ApiResponse.Error("未登录"));

                await _groupChatService.SendMessageAsync(groupId, userId, request.Content);
                return Ok(ApiResponse.Success("发送消息成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息失败");
                return BadRequest(ApiResponse.Error(ex.Message));
            }
        }
    }
}
